<template>
  <div class="header">
    <div class="logo" @click="goPage('/')" style="cursor:pointer">videoweb</div>
    <div class="header-search">
      <div class="search-wrap" @keyup.enter="goSearch('name')">
        <el-input class="handle-input" v-model="search_text" placeholder="请输入关键字" size="big" clearable>
        </el-input>
        <i class="el-icon-search" @click="goSearch('name')"></i>
      </div>
    </div>
    <div class="header-right">
      <ul class="header-nav" >
        <li class="user-collection">
          收藏记录
          <div class="collection-wrap">
            <ul class="collections" @click="gotoPlayVideo($event)">
              <li v-for="item in collectionData" :key="item.id" class="play" :id="item.id">
                <img class="videoImg" :src="getUrl(item.pic)">
                <div class="collection-info">
                  <p class="info-title">{{item.videoName||'视频已丢失'}}</p>
                  <p class="info-author"><i class="iconfont icon-avatar1"></i> {{item.authorName}}</p>
                </div>
              </li>
            </ul>
          </div>
        </li>
        <li class="user-history">
          历史记录
          <div class="history-wrap">
            <ul class="historys" @click="gotoPlayVideo($event)">
              <li v-for="item in historyData" :key="item.id"  class="play" :id="item.id">
                <img class="videoImg" :src="getUrl(item.pic)">
                <div class="history-info">
                  <p class="info-title">{{item.videoName||'视频已丢失'}}</p>
                  <p class="info-author"><i class="iconfont icon-avatar1 avatar"></i> {{item.authorName}}</p>
                </div>
              </li>
            </ul>
          </div>
        </li>
        <li @click="goPage('/contribute')" style="cursor:pointer">投稿视频</li>
      </ul>
      
      <div class="user">
        <div v-show="!loginIn" class="login" @click="goPage('/loginIn')">登录</div>
        <el-dropdown v-show="loginIn" trigger="click" style="cursor: pointer" @command="handleCommand">
          <span class="username">
            <img :src="getUrl(avatar)">
          </span>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item command="setting">设置</el-dropdown-item>
            <el-dropdown-item command="logout">退出登录</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </div>
    </div>

    <!-- 修改个人信息 -->
    <el-dialog title="修改用户" :visible.sync="editVisiable" center width="400px">
      <el-form :model="form" id="form" ref="form" :rules="rules" label-width="80px" :inline="false" size="small">
        <el-form-item prop="username" label="用户名" size="mini">
          <el-input name="username" v-model="form.username" placeholder="用户名"></el-input>
        </el-form-item>
        <el-form-item prop="orgPassword" label="原密码" size="mini">
          <el-input name="orgPassword" type="password" v-model="form.orgPassword" placeholder="原密码"></el-input>
        </el-form-item>
        <el-form-item prop="password" label="密码" size="mini">
          <el-input name="password2" type="password" v-model="form.password" placeholder="密码">
            <template v-if="form.password" slot="append">{{passwordlevel}}</template>
          </el-input>
        </el-form-item>
        <el-form-item prop="checkPass" label="确认">
          <el-input type="password" v-model="form.checkPass" placeholder="确认密码"></el-input>
        </el-form-item>
        <el-form-item prop="sex" label="性别">
          <el-radio-group v-model="form.sex">
            <el-radio name="sex" :label="0">女</el-radio>
            <el-radio name="sex" :label="1">男</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item prop="email" label="邮箱" size="mini">
          <el-input name="email" v-model="form.email" placeholder="邮箱"></el-input>
        </el-form-item>
        <el-form-item prop="birth" label="生日" size="mini">
          <el-date-picker name="birth" v-model="form.birth" placeholder="选择日期" size="mini" style="width:100%"></el-date-picker>
        </el-form-item>
        <el-form-item prop="introduction" label="签名" size="mini">
          <el-input name="introduction" type="textarea" maxlength="200" v-model="form.introduction" placeholder="签名"></el-input>
        </el-form-item>
        <el-form-item prop="pic" label="头像" size="mini">
          <input type="file" name="file" id="video_pic">
        </el-form-item>
      </el-form>
      <span></span>
      <span slot="footer">
        <el-button type="primary" @click="editConsumer">确定</el-button>
        <el-button @click="editVisiable = false">取消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {getVideoById,getConsumerOfId,getConsumerOfId2,updateConsumer} from '../api/index'
import {mapGetters} from 'vuex'
import {mixin} from '../mixins/index'
import {menuList} from '../assets/data/header'
export default {
  name:'the-header',
  mixins:[mixin],
  data(){
    //检查密码
    var validatePassword = (rule,value,callback) =>{
      if(value === ''||value===undefined){
        return 
      }else if(value.length<6){
        callback(new Error('密码不得少于6位'))
      }else{
        if(this.form.checkPass !== ''){
          this.$refs.form.validateField('checkPass')
        }
      }
      callback()
    }
    var validatePassword2 = (rule,value,callback) =>{
      if(value === ''||value===undefined){
        return 
      }else if(value !== this.form.password){
        callback(new Error('两次输入密码不一致'))
      }else{
        callback()
      }
    }
    return {
      search_text:'',  //搜索关键字
      menuList:[],  //用户下拉菜单
      collectionData:[],
      collectionData2:[],
      historyData:[],
      historyData2:[],
      editVisiable:false,
      form:{  //修改用户表
        id:'',
        username:'',
        orgPassword:'',
        orgPassword2:'',
        password:'',
        sex:'',
        email:'',
        birth:'',
        introduction:'',
      },
      rules:{
        username:[
          {required:true,trigger:'blur',message:'请输入用户名'}
        ],
        orgPassword:[
          {required:true,message:'请输入原密码'}
        ],
        password:[
          {required:false,validator:validatePassword,trigger:'blur'}
        ],
        checkPass:[
          {required:false,validator:validatePassword2,trigger:'blur'}
        ],
        sex:[
          {required:true,message:'请选择性别'}
        ],
        birth:[
          {required:true,message:'请选择日期',trigger:'change'}
        ],
        email:[
          {required:true,message:'请输入电子邮箱',trigger:'blur'},
          {type:'email',message:'请输入正确的电子邮箱地址',trigger:['blur','change']}
        ],
        introduction:[
          {required:false,message:'请输入签名',trigger:'blur'},
        ],
      }
    }
  },
  computed:{
    ...mapGetters([
      'username',
      'loginIn',
      'avatar',
      'collection',
      'history',  
    ]),
    //计算密码强度
    passwordlevel(){
      let level;
      if(/\d/.test(this.form.password) && /[a-z]/.test(this.form.password) && /[A-Z]/.test(this.form.password)){
        level = '强'
      }else if(/^\d+$/.test(this.form.password) || /^[A-Z]+$/.test(this.form.password) || /^[a-z]+$/.test(this.form.password)){
        level = '弱'
      }else{
        level = '中'
      }
      return level
    },
  },
  created(){
    this.menuList = menuList
    if (this.loginIn) {
      this.getNewConsumerData()
    }
  },
  mounted(){
    var _this = this
    document.getElementsByClassName('user-collection')[0].addEventListener('mouseenter',function(){
      for(let i in _this.collection){
        getVideoById(_this.collection[i])
          .then(res =>{
            _this.collectionData2[i] = res
          })
      }
      setTimeout(() => {
        _this.collectionData = _this.collectionData2
      }, 100);
    })
    document.getElementsByClassName('user-history')[0].addEventListener('mouseenter',function(){
      for(let i in _this.history){
        getVideoById(_this.history[i])
          .then(res =>{
            _this.historyData2[i] = res
          })
      }
      setTimeout(() => {
        _this.historyData = _this.historyData2
      }, 100);
    })
  },
  methods:{
    //跳转页面
    goPage(path){
      if(!this.loginIn && !(path == '/loginIn'||path == '/'||path == '/search')){
        this.notify('请先登录','warning')
      }else{
        this.$router.push({path:path});
      }
    },
    //头像下拉框
    handleCommand(command){
      if (command == 'logout') {
        this.$store.commit('setLoginIn',false)
        this.$store.commit('setUserId','')
        this.$store.commit('setUsername','')
        this.$store.commit('setAvatar',null)
        this.$store.commit('setCollection',null)
        this.$store.commit('setHistory',null)
        this.$store.commit('setPraise',null)
        this.$store.commit('setCommentPraise',null)
      }
      else if (command == 'setting') {
        this.handleEdit()
      }
    },
    handleEdit(){
      getConsumerOfId2(this.userId)
        .then(res =>{
          this.form = {
            id:res.id,
            username:res.username,
            orgPassword2:res.password,
            sex:res.sex,
            email:res.email,
            birth:res.birth,
            introduction:res.introduction,
          }
        })
      this.editVisiable = true
    },
    editConsumer(){
      if (this.form.orgPassword == this.form.orgPassword2) {
        if (this.form.password2 == '') {
          this.form.password = this.form.orgPassword2
        }
        var formData = new FormData(document.getElementById("form"));
        formData.append('id',this.form.id)
        formData.append('password',this.form.password)
        updateConsumer(formData)
        .then(res =>{
          if(res.code == 1){
            this.notify("修改成功","success")
            this.getNewConsumerData()
          }else{
            console.log(res.msg);
            this.notify("修改失败","error")
          }
        }).catch(err => {
          console.log(err)
        })
        this.editVisiable = false;
      }else{
        this.notify('原密码输入错误','warning')
      }
    },
    //更新数据
    getNewConsumerData(){
      getConsumerOfId(this.userId)
        .then(res =>{
          this.$store.commit('setUsername',res.username)
          this.$store.commit('setAvatar',res.avatar)
        })
    }
  }
}
</script>

<style scoped>
@import '../assets/css/theHeader.css';
</style>